from django.http import JsonResponse
from django.shortcuts import render, redirect

from order_platform import settings
from utils.response import BaseResponse
from web import models
from web.forms.account import LoginForm, SmsLoginForm, mobileForm, EmailLoginForm, emailForm


def login(request):
    if request.method == 'GET':
        form = LoginForm()
        return render(request, "login.html", {'form': form})

    # 1. 接收并获取数据（非空校验 - Form组件 & ModelForm组件）
    form = LoginForm(request.POST)
    if not form.is_valid():
        print(form.errors)
        return render(request, "login.html", {'form': form})
    # print('数据格式正确')

    # 2. 去数据库校验
    data_dict = form.cleaned_data
    role = data_dict.pop('role')
    if role == "1":
        user_obj = models.Administrator.objects.filter(active=1).filter(**data_dict).first()
    else:
        user_obj = models.Customer.objects.filter(active=1).filter(**data_dict).first()
    # print('开始校验')

    # 2.1 校验失败
    if not user_obj:
        # form.add_error('username', 'xxx')# 手动添加错误信息
        return render(request, "login.html", {'form': form, 'error': '用户名或密码错误'})

    # 2.2 校验成功，将用户信息写入session，跳转到项目后台（中间件会使用添加到session的用户信息做校验）
    # print('校验成功')
    role_mapping = {'1': 'ADMIN', '2': 'CUSTOMER'}
    user_dict = {'role': role_mapping.get(role), 'name': user_obj.username, 'id': user_obj.id}
    request.session[settings.MY_SESSION_KEY] = user_dict

    # 3. 跳转
    return redirect(settings.LOGIN_HOME)


def send_sms(request):
    res = BaseResponse()
    # 1. 校验数据格式
    form = mobileForm(request.POST)
    if not form.is_valid():
        res.detail = form.errors
        return JsonResponse(res.dict, json_dumps_params={'ensure_ascii': False})

    res.status = True
    return JsonResponse(res.dict)


def sms_login(request):
    if request.method == 'GET':
        form = SmsLoginForm()
        return render(request, "sms_login.html", {'form': form})

    res = BaseResponse()

    # 1. 数据校验，手机格式校验，角色
    form = SmsLoginForm(request.POST)
    if not form.is_valid():
        res.detail = form.errors
        return JsonResponse(res.dict)
    # 3. 登录+注册
    # 本业务不合适自动注册，手机号不存在提示错误
    role = form.cleaned_data['role']
    mobile = form.cleaned_data['mobile']
    if role == "1":
        user_obj = models.Administrator.objects.filter(mobile=mobile, active=1).first()
    else:
        user_obj = models.Customer.objects.filter(mobile=mobile, active=1).first()

    if not user_obj:
        res.detail = {'mobile': ['手机号不存在']}
        return JsonResponse(res.dict)
    # 校验成功，将用户信息写入session，跳转到项目后台
    role_mapping = {'1': 'ADMIN', '2': 'CUSTOMER'}
    request.session[settings.MY_SESSION_KEY] = {'role': role_mapping.get(role), 'name': user_obj.username,
                                                'id': user_obj.id}
    return redirect(settings.LOGIN_HOME)


def send_email(request):
    res = BaseResponse()
    # 1. 校验数据格式
    form = emailForm(request.POST)
    if not form.is_valid():
        res.detail = form.errors
        return JsonResponse(res.dict, json_dumps_params={'ensure_ascii': False})

    res.status = True
    return JsonResponse(res.dict)


def email_login(request):
    if request.method == 'GET':
        form = EmailLoginForm()
        return render(request, "email_login.html", {'form': form})

    res = BaseResponse()

    # 1. 数据校验，邮箱格式校验，角色
    form = EmailLoginForm(request.POST)
    if not form.is_valid():
        res.detail = form.errors
        return JsonResponse(res.dict)
    # 3. 登录+注册
    # 本业务不合适自动注册，邮箱不存在提示错误
    role = form.cleaned_data['role']
    email = form.cleaned_data['email']
    if role == "1":
        user_obj = models.Administrator.objects.filter(email=email, active=1).first()
    else:
        user_obj = models.Customer.objects.filter(email=email, active=1).first()

    if not user_obj:
        res.detail = {'email': ['邮箱未注册，请联系管理员']}
        return JsonResponse(res.dict)

    # 校验成功，将用户信息写入session，跳转到项目后台
    role_mapping = {'1': 'ADMIN', '2': 'CUSTOMER'}
    request.session[settings.MY_SESSION_KEY] = {'role': role_mapping.get(role), 'name': user_obj.username,
                                                'id': user_obj.id}
    res.status = True
    res.data = settings.LOGIN_HOME
    return JsonResponse(res.dict)


def logout(request):
    """ 注销 """
    request.session.clear()
    return redirect(settings.LOGIN_URL)


def home(request):
    return render(request, 'home.html')
